<template>
    <div>
        <!--        面包屑-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/goods">商品管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
        <!--        卡片区-->
        <el-card>
            <!--            添加分类按钮-->
            <el-row>
                <el-col :span="4">
                    <el-button type="primary" @click="showAddCategoryDialog">添加分类</el-button>
                </el-col>
            </el-row>
            <!--            表格-->
            <el-table
                    :data="categories"
                    style="width: 100%;margin-bottom: 20px;"
                    row-key="cat_id"
                    border
                    :default-expand-all="false"
                    :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
                <el-table-column
                        prop="cat_name"
                        label="分类名称"
                        min-width="180">
                </el-table-column>
                <el-table-column
                        label="是否有效"
                        min-width="180">
                    <template #default="scope">
                        <i v-if="!scope.row.cat_deleted" style="color:lawngreen" class="el-icon-success"></i>
                        <i v-else class="el-icon-error" style="color: red"></i>
                    </template>
                </el-table-column>
                <el-table-column
                        label="级别"
                        min-width="180">
                    <template #default="scope">
                        <el-tag v-if="scope.row.cat_level===0">一级</el-tag>
                        <el-tag type="success" v-if="scope.row.cat_level===1">二级</el-tag>
                        <el-tag type="warning" v-if="scope.row.cat_level===2">三级</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                        label="操作"
                        min-width="180">
                    <template #default="scope">
                        <el-button size="mini" type="primary"
                                   @click="showEditCategoryDialog(scope.row)"
                                   class="el-icon-edit">编辑</el-button>
                        <el-button size="mini" type="danger"
                                   @click="deleteCategory(scope.row.cat_id)"
                                   class="el-icon-delete">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!--            分页-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-sizes="[2, 5, 10, 15]"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
            <!--            添加分类dailog-->
            <el-dialog title="添加分类"
                       width="30%"
                       v-model="addCategoryDialogVisible">
                <el-form label-width="100px"
                         ref = 'addCategoryFormRef'
                         :model="addCategoryForm"
                         :rules="addCategoryFormRules">
                    <el-form-item label="分类名称：" prop="cat_name">
                        <el-input placeholder="请输入分类名称"
                                  v-model="addCategoryForm.cat_name"></el-input>
                    </el-form-item>
                    <el-form-item label="父级分类：">
                        <el-cascader
                                style="width: 100%"
                                :clearable="true"
                                :props="cascaderParameters"
                                v-model="selectedKeys"
                                :options="parentCategories"
                                @change="handleChange">
                        </el-cascader>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <el-button @click="closeAddCategoryDialog">取消</el-button>
                    <el-button type="primary" @click="addCategory">确定</el-button>
                </template>
            </el-dialog>
            <!--            编辑分类的dialog-->
            <el-dialog title="编辑分类"
                       width="30%"
                       :before-close="closeEditCategoryDialog"
                       v-model="editCategoryDialogVisible">
                <label >原分类名：</label>
                <el-input
                        style="width: 70%"
                        v-model="editCate.cat_name"></el-input><br/>
                <label >新分类名：</label>
                <el-input placeholder="请输入新分类名"
                          style="width: 70%"
                          v-model="cat_name"
                          ref="catNameRef"></el-input>
                <template #footer>
                    <el-button @click="closeEditCategoryDialog">取消</el-button>
                    <el-button type="primary" @click="editCategory">确定</el-button>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script>
  export default {
    name: "GoodCategory",
    data(){
      return {
        addCategoryDialogVisible:false,//添加分类dialog
        addCategoryForm:{
          cat_name:'',
          cat_pid:0,
          cat_level:0,//0-1级，1-2级，2-3级
        },
        addCategoryFormRules:{
          cat_name:[{required:true,message:'请输入分类名称',trigger:'blur'}],
        },

        categories:[],//分类列表
        queryInfo:{
          type:3,
          pagenum:1,
          pagesize:5,
        },
        total:0,//总条数

        columns:[//配置TreeTable
          {
            label:'分类名称',
            prop:'cat_name'
          },
        ],

        parentCategories:[],//父级分类列表
        cascaderParameters:{
          expandTrigger: 'hover',
          label:'cat_name',
          value:'cat_id',
          children:'children',
          checkStrictly: true,//能够随意选择一级
        },
        selectedKeys:null,//级联选择器选择结果
        //编辑分类
        editCategoryDialogVisible:false,
        cat_name:'',//新名称
        editCate: {},//
      }
    },
    created() {
      this.getGoodsCategories();
    },
    methods:{
      //获取父级分类数据
      async getParentCategories(){
        const {data:res} = await this.$http.get('/categories',{params:{
            type:2,
          }});
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }else{
          this.parentCategories = res.data;
          console.log(res.data);
        }
      },
      //级联选择器发生变化
      handleChange(){
        //console.log(val);
        this.addCategoryForm.cat_pid = (this.selectedKeys && this.selectedKeys[this.selectedKeys.length-1]) || 0 ;
        this.addCategoryForm.cat_level = (this.selectedKeys && this.selectedKeys.length) || 0;
        console.log(this.addCategoryForm)
      },
      //添加分类
      async addCategory(){
        const {data:res} = await this.$http.post('/Categories',this.addCategoryForm);
        if(res.meta.status !== 201){
          return this.$message.error(res.meta.msg);
        }else{
          return this.$message.success(res.meta.msg);
        }
        this.closeAddCategoryDialog();
        this.getGoodsCategories();
      },
      async getGoodsCategories(){
        const {data:res} = await this.$http.get('/categories',{params:this.queryInfo});
        console.log(res);
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }else{
          this.categories = res.data.result;
          this.total = res.data.total;
        }
      },
      //展示添加分类dialog
      showAddCategoryDialog(){
        this.addCategoryDialogVisible = true;
        this.getParentCategories();
      },
      closeAddCategoryDialog(){
        this.addCategoryDialogVisible = false;
        this.$refs.addCategoryFormRef.resetFields();
        this.addCategoryForm.cat_pid = 0;
        this.addCategoryForm.cat_level = 0;
        this.selectedKeys = null;
      },
      //分页
      handleSizeChange(val) {
        this.queryInfo.pagesize = val;
        this.getGoodsCategories();
      },
      handleCurrentChange(val) {
        this.queryInfo.pagenum = val;
        this.getGoodsCategories();
      },
      //根据id删除分类
      async deleteCategory(id){
        const res = await this.$confirm('确定删除个这个分类吗？','提示',{
          confirmButtonText:'确定',
          cancelButtonText:'取消',
          type:'warning',
        }).catch(err=>console.log(err));
        if(res==='confirm'){
          const {data:res} = await this.$http.delete(`/categories/${id}`);
          if(res.meta.status !== 200){
            return this.$message.error(res.meta.msg);
          }
          this.$message.success(res.meta.msg);
          this.getGoodsCategories();
        }else{
          this.$message.info('用户取消操作');
        }
      },
      //显示编辑
      showEditCategoryDialog(cate){
        this.editCategoryDialogVisible = true;
        this.editCate = cate;
      },
      closeEditCategoryDialog(){
        this.editCategoryDialogVisible = false;
        this.editCate = {};
        this.cat_name = '';
      },
      async editCategory(){
        if(!this.cat_name){
          this.$message.warning('请输入新分类名');
          this.$refs.catNameRef.focus();
        }else{
          const {data:res} = await this.$http.put(`categories/${this.editCate.cat_id}`,{cat_name:this.cat_name});
          if(res.meta.status !== 200){
            return this.$message.error(res.meta.msg);
          }else{
            this.$message.success(res.meta.msg);
            this.closeEditCategoryDialog();
            this.getGoodsCategories();
          }
        }
      },
    }
  }
</script>

<style scoped>

</style>
